package com.example.bootes.config;

import com.example.bootes.param.Constants;
import com.example.bootes.utils.TraceIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Administrator
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果有上层调用就用上层的ID
//        String traceId = request.getHeader(Constants.TRACE_ID);
//        if (traceId == null) {
//            traceId = TraceIdUtil.getTraceId();
//        }
        MDC.put(Constants.TRACE_ID, TraceIdUtils.getTraceId());
        log.info("拦截器进入调用：{}",MDC.get(Constants.TRACE_ID));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
          log.info("拦截器返回调用：{}",MDC.get(Constants.TRACE_ID));
        //调用结束后删除
        MDC.remove(Constants.TRACE_ID);
    }
}
